using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Data;

namespace WPFTemplateLib.Attached
{
	/// <summary>
	/// 上下文（右键）菜单附加属性帮助类
	/// </summary>
	public class ContextMenuAttached
	{
		#region [附加属性] 是否允许左键触发
		public static bool GetIsLeftClickEnabled(DependencyObject obj)
		{
			return (bool)obj.GetValue(IsLeftClickEnabledProperty);
		}
		/// <summary>
		/// 设置 是否允许左键触发
		/// </summary>
		public static void SetIsLeftClickEnabled(DependencyObject obj, bool value)
		{
			obj.SetValue(IsLeftClickEnabledProperty, value);
		}
		/// <summary>
		/// [附加属性] 是否允许左键触发
		/// </summary>
		public static readonly DependencyProperty IsLeftClickEnabledProperty =
			DependencyProperty.RegisterAttached("IsLeftClickEnabled", typeof(bool), typeof(ContextMenuAttached), new PropertyMetadata(false, IsLeftClickEnabledChangedCallback));
		/// <summary>
		/// 是否允许左键触发 变化处理方法
		/// </summary>
		private static void IsLeftClickEnabledChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var uiElement = d as UIElement;
			if(uiElement == null)
				return;

			bool isEnabled = e.NewValue is bool && (bool)e.NewValue;
			if(isEnabled)
			{
				if(uiElement is ButtonBase)
					((ButtonBase)uiElement).Click += OnMouseLeftButtonUp;
				else
					uiElement.MouseLeftButtonUp += OnMouseLeftButtonUp;
			}
			else
			{
				if(uiElement is ButtonBase)
					((ButtonBase)uiElement).Click -= OnMouseLeftButtonUp;
				else
					uiElement.MouseLeftButtonUp -= OnMouseLeftButtonUp;
			}
		}

		private static void OnMouseLeftButtonUp(object sender, RoutedEventArgs e)
		{
			var fe = sender as FrameworkElement;
			if(fe != null && fe.ContextMenu != null)
			{
				if(fe.ContextMenu.DataContext == null)
					fe.ContextMenu.SetBinding(FrameworkElement.DataContextProperty, new Binding { Source = fe.DataContext });

				fe.ContextMenu.IsOpen = true;
			}
		}
		#endregion
	}
}
